package com.wwl.collection.job.job1;

import java.io.*;
import java.util.TreeSet;

/**
 * 1 键盘上录入数据，以对象方式的存入到数据文件中data.psw
 * 2 将data.psw文件中的数据读出，并拍照某种方式排序显示
 * 3 Person类,Comparable,compareTo
 * TreeSet
 */
public class Test {
    public static void main(String[] args) throws IOException {
        TreeSet<Person> set=null;
        Test.writeFile("data.psw");
        set = Test.readFile("data.psw");
        System.out.println(set.size());
        System.out.println(set);
    }

    /**
     * 从键盘接收数据，将数据打包成Person对象的形式，存入文件中
     * 1 bufferedReader 读入，直到输入over
     * 2 IO重定向问题
     * @param fileName
     */

    public static void writeFile(String fileName){
        try {
            //FileInputStream fis = new FileInputStream(fileName);
            //System.setIn(fis);
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName));
            String line=br.readLine();
            while(!line.equals("over")){
                String[] arr = line.split(",");
                Person p = new Person(arr[0],Integer.parseInt(arr[1]));
                oos.writeObject(p);
                line=br.readLine();
            }
            oos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //从数据文件中读入数据，以Person的形式将数据写入到一个Treeset中，排序输出
    public static TreeSet<Person> readFile(String fileName){
        TreeSet<Person> set= new TreeSet<Person>();
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream(fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        while(true){
            Person p = null;
            try {
                p = (Person) ois.readObject();
                set.add(p);
            }catch (EOFException e){
                break;
            }catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return set;
    }
}
